﻿using HandyControl.Data;
using Prism.Commands;
using Prism.Events;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ZoneLineNew.Common;
using ZoneLineNew.Core.EventArgs;
using ZoneLineNew.Core.Extensions;
using ZoneLineNew.Models.StationConfig;
using ZoneLineNew.Services.DB;
using ZoneLineNew.Services.Message;

namespace ZoneLineNew.Controls {
    /// <summary>
    /// NonClientAreaControl.xaml 的交互逻辑
    /// </summary>
    public partial class NonClientAreaControl : UserControl {

        private readonly IMessageService _messageService;
        private readonly IEventAggregator _eventAggregator;
        private readonly IDbOperate<IFreeSqlMainContext> _mainDbOperate;

        public NonClientAreaControl() {
            InitializeComponent();
            _messageService = PrismIocInfo.GetInstanceByIoc<IMessageService>();
            _eventAggregator = PrismIocInfo.GetInstanceByIoc<IEventAggregator>();
            _mainDbOperate = PrismIocInfo.GetInstanceByIoc<IDbOperate<IFreeSqlMainContext>>();
        }

        private void ButtonLangs_OnClick(object sender, RoutedEventArgs e) {
            //if (e.OriginalSource is Button btn) {
            //    string langName = btn.Tag.ToString();
            //    PopupConfig.IsOpen = false;
            //    if (langName.Equals(AppSession.Config.Lang)) {
            //        return;
            //    }
            //    AppSession.Config.Lang = langName;
            //    AppSession.SaveAppConfig();
            //    ((App)Application.Current).UpdateLang(langName);
            //}
        }

        private void ButtonConfig_OnClick(object sender, RoutedEventArgs e) => PopupConfig.IsOpen = true;

        private void ButtonSkins_OnClick(object sender, RoutedEventArgs e) {
            if (e.OriginalSource is Button btn) {
                SkinType skinType = (SkinType)btn.Tag;
                PopupConfig.IsOpen = false;
                if (skinType.Equals(AppSession.Config.Skin)) {
                    return;
                }

                AppSession.Config.Skin = skinType;
                AppSession.SaveAppConfig();
                ((App)Application.Current).UpdateSkin(skinType);
            }
        }
        
        private void linkScan_Checked(object sender, RoutedEventArgs e) {
            Init("Open");
        }

        private void linkScan_Unchecked(object sender, RoutedEventArgs e) {
            Init("Close");
        }

        #region 扫码枪相关

        private SerialPort _scanSerial;

        private void Init(string cmd) {
            if (cmd == "Open") {
                var packageScanConfig = _mainDbOperate.GetModel<PackageScanBarConfig>(p => true);
                try {
                    if (_scanSerial == null) {
                        _scanSerial = new SerialPort();
                        _scanSerial.PortName = packageScanConfig.Port;
                        _scanSerial.BaudRate = 115200;
                        _scanSerial.DataBits = 8;
                        _scanSerial.StopBits = StopBits.One;
                        _scanSerial.Parity = Parity.None;
                        _scanSerial.DataReceived += _scanSerial_DataReceived;
                    }
                    _scanSerial.Close();
                    _scanSerial.Open();
                    if (_scanSerial.IsOpen) {
                        _messageService.GrowSuccess("连接成功！");
                    }
                } catch (Exception ex) {
                    linkScan.IsChecked = false;
                    _messageService.GrowError($"连接失败，{ex.Message}！");
                }
            } else {
                if (_scanSerial != null) {
                    _scanSerial?.Close();
                    _scanSerial?.Dispose();
                }
            }
        }

        ///// <summary>
        ///// 缸体码
        ///// </summary>
        //public const string _scanCylinderBlockCode = "ScanCylinderBlockCode";
        ///// <summary>
        ///// 标签码
        ///// </summary>
        //public const string _scanLabelCode = "ScanLabelCode";
        ///// <summary>
        ///// 装箱码
        ///// </summary>
        //public const string _scanBoxCode = "ScanBoxCode";
        /// <summary>
        /// 扫码
        /// </summary>
        public const string _scanCode = "ScanCode";

        private void _scanSerial_DataReceived(object sender, SerialDataReceivedEventArgs e) {
            Thread.Sleep(200);
            var lenght = _scanSerial.BytesToRead;
            var bytes = new byte[lenght];
            _scanSerial.Read(bytes, 0, lenght);
            var str = Encoding.UTF8.GetString(bytes).Replace("\n", "").Replace("\r", "");
            MessageData messageData = new MessageData() {
                Code = _scanCode,
                Parameters = new DialogParameters() {
                    { "Content", str}
                }
            };
            _eventAggregator.GetEvent<PubSubEventArgs>().Publish(messageData);
        }
        #endregion

    }
}
